﻿
package extremefx.anim.transitions {
	import extremefx.anim.transitions.ITransition;
	
	/**
	 * @author Marcelo Volmaro
	 */
	public class SmoothCD implements ITransition {

		private var _vel:Number;
		private var _smoothTime:Number;
		private var _omega:Number;
		private var _maxSpeed:Number;
		private var _ctime:Number;
		private var _lastIndex:Number;

		public function SmoothCD(pSmooth:Number, pMaxSpeed:Number = 0) {
			_vel = 0;
			_smoothTime = pSmooth;
			_omega = 2 / pSmooth;
			_maxSpeed = pMaxSpeed || 0;
			_ctime = 4 * pSmooth;
			_lastIndex = 0;
		}

		public function step(pCurrent:Number, pStart:Number, pChange:Number, pEnd:Number):Number {
			if (_lastIndex == 0) _lastIndex = pCurrent;
			
			var timeDelta:Number = pCurrent - _lastIndex;
			
			_lastIndex = pCurrent;
			
			var x:Number = _omega * timeDelta;
			var exp:Number = 1/(1 + x + .48 * x * x + .235 * x * x * x);
			var change:Number = pCurrent - pEnd;
	
			if (_maxSpeed){
				var maxChange:Number = _maxSpeed * _smoothTime;
				change = Math.min(Math.max(-maxChange, change), maxChange);
			}
	
			var temp:Number = (_vel + _omega * change) * timeDelta;
			_vel = (_vel - _omega * temp) * exp;

			return pEnd + (change + temp) * exp;
		}
	}
}
